package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 定义全局变量
var (
	clientOptions *options.ClientOptions
	once          sync.Once
	client        *mongo.Client
	ctx           context.Context
	cancel        context.CancelFunc
)

// 初始化clientOptions的函数
func InitClientOptions() {
	once.Do(func() {
		clientOptions = options.Client().ApplyURI("mongodb://mongoadmin1:mongoadmin1@124.220.104.235:27017/test01?authSource=admin")
		ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)

		var err error
		client, err = mongo.Connect(ctx, clientOptions)
		if err != nil {
			log.Fatalf("Failed to connect to MongoDB: %v", err)
		}

		// 检查连接
		err = client.Ping(ctx, nil)
		if err != nil {
			log.Fatalf("Failed to ping MongoDB: %v", err)
		}
	})

}

// 定义一个文档结构体
type Person struct {
	Name  string
	Age   int
	Email string
}

type WebInfo struct {
	Uid             string `bson:"uid"`
	Name            string `bson:"name"`
	Url             string `bson:"url"`
	Weight          int32  `bson:"weight"`
	UserId          string `bson:"userId"`
	DelFlag         string `bson:"delFlag"`
	WebCategoryId   string `bson:"webCategoryId"`
	WebCategoryName string `bson:"webCategoryName"`
}

func main1() {
	// 设置MongoDB连接选项
	//clientOptions := options.Client().ApplyURI("mongodb://mongoadmin1:mongoadmin1@124.220.104.235:27017/test01?authSource=admin")
	InitClientOptions()
	// 连接到MongoDB
	// ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	// defer cancel()
	// client, err := mongo.Connect(ctx, clientOptions)
	// if err != nil {
	// 	log.Fatal(err)
	// }

	getList()

}

func insertResult() {
	// 获取数据库和集合
	collection := client.Database("testdb").Collection("people")
	// 插入单个文档
	person := Person{
		Name:  "John Doe",
		Age:   30,
		Email: "johndoe@example.com",
	}

	insertResult, err := collection.InsertOne(ctx, person)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

func getList() {
	InitClientOptions()
	// 获取数据库和集合
	collection := client.Database("testdb").Collection("web_info")
	// 查询文档
	filter := bson.D{{}}
	cur, err := collection.Find(ctx, filter)
	var results []WebInfo
	if err = cur.All(context.Background(), &results); err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result)
	}
}
